package com.zem.imos.Service;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zem.imos.Entity.*;
import com.zem.imos.Entity.Enum.RegisterStatus;
import com.zem.imos.Entity.Params.ParamsDoctor;
import com.zem.imos.Entity.Params.ParamsPatient;
import com.zem.imos.Mapper.*;
import com.zem.imos.Util.JWT;
import com.zem.imos.Util.Validate;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;
import java.util.TimeZone;

@Service
public class DoctorService {
    @Autowired
    DoctorMapper doctorMapper;
    @Autowired
    UserMapper userMapper;
    @Autowired
    PatientMapper patientMapper;
    @Autowired
    RegisterMapper registerMapper;
    @Autowired
    DrugsorderMapper drugsorderMapper;
    @Autowired
    DrugsMapper drugsMapper;
    @Autowired
    VisitMapper visitMapper;
    @Autowired
    LaborScheduleMapper laborScheduleMapper;

    /**
     * 医生登陆
     * @author ZEM
     * @Time 2021/11/20
     * @Description 用户名密码登陆 返回用户的token
     */
    public RespEntity login(String username, String password)
    {
        QueryWrapper<Doctor> queryWrapper = new QueryWrapper();
        queryWrapper.eq("username",username);
        ParamsDoctor paramsDoctor = doctorMapper.selectOneDoctor(queryWrapper);
        if(paramsDoctor == null)
        {
            RespEntity res = new RespEntity(new RespEntity.CRespCode(400,"密码或用户名错误"));
            return res;
        }

        if(paramsDoctor.getRole() != 0)
        {
            RespEntity res = new RespEntity(new RespEntity.CRespCode(400,"请使用医生账号登陆"));
            return res;
        }
        if(paramsDoctor.getPassword().equals(DigestUtils.md5DigestAsHex(password.getBytes())))
        {
            JWT jwt = new JWT();
            String token = jwt.createJwtForDoctor(paramsDoctor, 30*1000*60*60*24L);
            JSONObject object = new JSONObject();
            object.put("token",token);
//            object.put("user",user);
            RespEntity res = new RespEntity(new RespEntity.CRespCode(200,"连接成功"),object);
            return res;
        }
        RespEntity res = new RespEntity(new RespEntity.CRespCode(400,"密码或用户名错误"));
        return res;
    }

    /**
     * 医生开药
     * @author ZEM
     * @Time 2021/11/24
     * @Description 医生就诊时给用户开药
     * 未测试
     */
    public RespEntity registerbydoc(HttpServletRequest request,List<DrugsOrder> drugslist)
    {
        String token = request.getHeader("token");
        Claims claims = JWT.parseJwt(token);
        if(claims.get("role").equals("医生"))
        {
            System.out.println(drugslist.get(0));
            Register register = registerMapper.selectById(drugslist.get(0).getRegisterId());
            if(register != null)
            {
                for(int i=0;i<drugslist.size();i++)
                {
                    // 药品数量要改动  且药品订单要提交 因此需要两个实体
                    Drug drugs = new Drug();
                    DrugsOrder drugsorder = new DrugsOrder();

                    // 药品订单
                    drugsorder.setDrugId(drugslist.get(i).getDrugId());

                    /**
                     * ZSQ
                     * 属性删除了，这里还要吗
                     */
                    //drugsorder.setDrugName(drugslist.get(i).getDrugName());

                    drugsorder.setDrugsOrderNum(drugslist.get(i).getDrugsOrderNum());
                    long nowTime =System.currentTimeMillis();
                    drugsorder.setDrugTimestamp(nowTime);
                    drugsorder.setRegisterId(drugslist.get(i).getRegisterId());

                    // 药品库存
                    drugs.setId(drugslist.get(i).getId());
                    drugs.setDrugNum(drugsMapper.selectById(drugslist.get(i).getDrugId()).getDrugNum() - drugslist.get(i).getDrugsOrderNum());
                    drugsorderMapper.insert(drugsorder);
                    drugsMapper.updateById(drugs);
                }
                // 更新患者看诊状态
                register.setStatus(1);
                registerMapper.updateById(register);
                RespEntity res = new RespEntity(new RespEntity.CRespCode(200,"开药成功！"));
                return res;
            }
            else
            {
                RespEntity res = new RespEntity(new RespEntity.CRespCode(400,"挂号id不存在"));
                return res;
            }
        }
        RespEntity res = new RespEntity(new RespEntity.CRespCode(400,"获取信息失败"));
        return res;

    }

    /**
     * 医生注册
     * @author ZEM
     * @Time 2021/11/25
     * @Description 医生注册账号
     */
    public RespEntity doctorlogon(ParamsDoctor paramsDoctor)
    {
        QueryWrapper<Doctor> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username",paramsDoctor.getUsername());
        if(doctorMapper.selectOneDoctor(queryWrapper)!= null)
        {
            RespEntity res = new RespEntity(new RespEntity.CRespCode(400,"用户名已存在"));
            return res;
        }
        if (paramsDoctor.getPassword() != null)
            paramsDoctor.setPassword(DigestUtils.md5DigestAsHex(paramsDoctor.getPassword().getBytes()));

        User user = new User(paramsDoctor);
        Doctor doctor = new Doctor(paramsDoctor);
        userMapper.insert(user);
        doctor.setUserId(user.getId());
        doctorMapper.insert(doctor);
        RespEntity res = new RespEntity(new RespEntity.CRespCode(200,"用户新增成功"),doctor);
        return res;
    }


    /**
     * 获取当天挂号的患者
     * @author ZEM
     * @Time 2021/11/24
     * @Description 医生获取当天挂号的患者
     */
    public RespEntity getregister(HttpServletRequest request, Page page)
    {
        String token = request.getHeader("token");
        Claims claims = JWT.parseJwt(token);
        if(claims.get("role").equals("医生"))
        {
            Doctor doctor = doctorMapper.selectById((Long)claims.get("id"));
            if(doctor != null)
            {
                long nowTime =System.currentTimeMillis();
                long todayStartTime =nowTime - ((nowTime + TimeZone.getDefault().getRawOffset()) % (24 * 60 * 60 * 1000L));
                QueryWrapper<Register> queryWrapper=new QueryWrapper();
                queryWrapper.eq("doctor_id", doctor.getUserId());
                queryWrapper.eq("date",todayStartTime);
                IPage<List<ParamsPatient>> registerList = registerMapper.selectRegisterPatient(page,queryWrapper);
                System.out.println(registerList);
                RespEntity res = new RespEntity(new RespEntity.CRespCode(200,"成功"),registerList);
                return res;
            }
            else
            {
                RespEntity res = new RespEntity(new RespEntity.CRespCode(400,"医生不存在"));
                return res;
            }
        }
        RespEntity res = new RespEntity(new RespEntity.CRespCode(400,"获取信息失败"));
        return res;
    }

    /**
     * 获取就诊信息
     * @author ZEM
     * @Time 2021/11/24
     * @Description 医生获取所有已经就诊了的患者信息，即获取该医生看诊的所有患者。
     */
    public RespEntity getvisit(HttpServletRequest request , Page page )
    {
        String token = request.getHeader("token");
        Claims claims = JWT.parseJwt(token);
        if(claims.get("role").equals("医生"))
        {
            QueryWrapper<Register> queryWrapper=new QueryWrapper();
            queryWrapper.eq("status",1);
            queryWrapper.eq("doctor_id", (Long)claims.get("id"));
            // System.out.println((Long)claims.get("id")); //test
            IPage<List<ParamsPatient>> registerList = registerMapper.selectRegisterPatient(page,queryWrapper);
            RespEntity res = new RespEntity(new RespEntity.CRespCode(200,"成功"),registerList);
            return res;

        }
        RespEntity res = new RespEntity(new RespEntity.CRespCode(400,"获取信息失败"));
        return res;

    }
    /**
     * 通过名称模糊查找药品
     * @author ZEM
     * @Time 2021/11/24
     * @Description 医生获取所有已经就诊了的患者信息，即获取该医生看诊的所有患者。
     */
    public RespEntity selectdrugsnamebydoctor(HttpServletRequest request,Page page, String name)
    {
        String token = request.getHeader("token");
        Claims claims = JWT.parseJwt(token);
        if(claims != null)
        {
            if(claims.get("role").equals("医生") )
            {
                QueryWrapper<Drug> queryWrapper=new QueryWrapper();
                queryWrapper.like("drug_name", name);
                IPage<List<Drug>> drugs = drugsMapper.selectPage(page,queryWrapper);
                RespEntity res = new RespEntity(new RespEntity.CRespCode(200,"药品查找成功"),drugs);
                return res;
            }
            RespEntity res = new RespEntity(new RespEntity.CRespCode(400,"身份验证错误，需要医生。"));
            return res;

        }
        RespEntity res = new RespEntity(new RespEntity.CRespCode(400,"获取用户token信息失败"));
        return res;

    }

    /**
     * 获取就诊信息
     * @author ZEM
     * @Time 2021/11/24
     * @Description 医生获取所有已经就诊了的患者信息，即获取该医生看诊的所有患者。
     */
    public RespEntity getisvisitinfobydoctor(HttpServletRequest request,Page page)
    {
        String token = request.getHeader("token");
        Claims claims = JWT.parseJwt(token);
        if(claims != null)
        {
            if(claims.get("role").equals("医生") )
            {
                QueryWrapper<Register> queryWrapper = new QueryWrapper<>();
                queryWrapper.eq("doctor_id", (Long)claims.get("id"));
                queryWrapper.eq("status", 1);
                IPage<List<ParamsPatient>> registerList = registerMapper.selectRegisterPatient(page,queryWrapper);
                RespEntity res = new RespEntity(new RespEntity.CRespCode(200,"就诊患者信息查找成功"), registerList);
                return res;
            }
            RespEntity res = new RespEntity(new RespEntity.CRespCode(400,"身份验证错误，需要医生。"));
            return res;
        }
        RespEntity res = new RespEntity(new RespEntity.CRespCode(400,"获取用户token信息失败"));
        return res;
    }
    /**
     * 药剂师获取患者药品单
     * @author ZEM
     * @Time 2021/11/24
     * @Description 药剂师返回此患者的待出药品单给药品管理员
     */
    public RespEntity getdrugsorderbydoctorisvisit(HttpServletRequest request, Page page, int rid)
    {
        String token = request.getHeader("token");
        Claims claims = JWT.parseJwt(token);
        if(claims != null)
        {
            if(claims.get("role").equals("医生") )
            {
                Register register = registerMapper.selectById(rid);
                if(register == null)
                {
                    RespEntity res = new RespEntity(new RespEntity.CRespCode(200,"没有就诊记录"));
                    return res;
                }
                else if (register.getStatus().getValue() == 1)
                {

                        QueryWrapper<Register> queryWrapper = new QueryWrapper();
                        queryWrapper.eq("register.id", rid);
                        IPage<List<Map>> map = registerMapper.getdrugsorderbydoctorisvisit(page, queryWrapper);
                        RespEntity res = new RespEntity(new RespEntity.CRespCode(200,"成功返回出药记录"), map);
                        return res;

                }
                RespEntity res = new RespEntity(new RespEntity.CRespCode(400,"未就诊，无开药信息。"));
                return res;
            }
            RespEntity res = new RespEntity(new RespEntity.CRespCode(400,"身份验证错误，需要医生。"));
            return res;
        }
        RespEntity res = new RespEntity(new RespEntity.CRespCode(400,"获取用户token信息失败"));
        return res;
    }


    /**
     * 获取用户列表
     * @author ZEM
     * @Time 2021/11/24
     * @Description 医生获取满足条件的患者信息列表
     */
    public RespEntity getuserinfobydoctor(HttpServletRequest request, Page page, ParamsPatient user)
    {
        String token = request.getHeader("token");
        Claims claims = JWT.parseJwt(token);
        if(claims != null)
        {

            if(claims.get("role").equals("医生") )
            {
                QueryWrapper<ParamsPatient> queryWrapper=new QueryWrapper();
                queryWrapper.eq("user.role", 1);
                if(user.getId()!=null)
                    queryWrapper.eq("patient.id", user.getId());
                if(user.getName()!=null)
                    queryWrapper.like("name", user.getName());
                if(user.getUsername()!=null)
                    queryWrapper.eq("username", user.getUsername());
                if(user.getGender()!=null)
                    queryWrapper.eq("gender",user.getGender());
                if(user.getIdNum()!=null)
                    queryWrapper.eq("id_num",user.getIdNum());
                if(user.getPhone()!=null)
                    queryWrapper.eq("phone",user.getPhone());

                IPage<List<ParamsPatient>> users= patientMapper.selectPatientList(page,queryWrapper);
                RespEntity res = new RespEntity(new RespEntity.CRespCode(200,"用户查找成功"),users);
                return res;
            }
            RespEntity res = new RespEntity(new RespEntity.CRespCode(400,"身份验证错误，需要医生。"));
            return res;

        }
        RespEntity res = new RespEntity(new RespEntity.CRespCode(400,"获取用户token信息失败"));
        return res;

    }

    /**
     * 医生提交就诊结果
     * @author ZEM
     * @Time 2021/11/24
     * @Description  医生提交就诊结果，包括registerid 症状 和结果
     */
    public RespEntity insertvisit(HttpServletRequest request, Visit visit)
    {
        String token = request.getHeader("token");
        Claims claims = JWT.parseJwt(token);
        if(claims != null)
        {

            if(claims.get("role").equals("医生") )
            {

                visitMapper.insert(visit);
                Register register = new Register();
                register.setStatus(1);
                register.setId(visit.getRegisterId());
                registerMapper.updateById(register);
                RespEntity res = new RespEntity(new RespEntity.CRespCode(200,"就诊信息修改成功"));
                return res;
            }
            RespEntity res = new RespEntity(new RespEntity.CRespCode(400,"身份验证错误，需要医生。"));
            return res;

        }
        RespEntity res = new RespEntity(new RespEntity.CRespCode(400,"获取用户token信息失败"));
        return res;

    }

    /**
     * 管理员获取排班信息
     * @author ZEM
     * @Time 2021/12/02
     * @Description 管理员获取排班信息
     */

    public RespEntity  selectScheduleStatus(HttpServletRequest request, Long date, Long id )
    {
        String token = request.getHeader("token");
        Claims claims = JWT.parseJwt(token);
        if(claims != null)
        {
            if(claims.get("role").equals("医生"))
            {
                QueryWrapper queryWrapper = new QueryWrapper<>();
                queryWrapper.eq("date",date);
                queryWrapper.eq("doctor.id",id);
                List<Map> schedule = laborScheduleMapper.selectSchedule(queryWrapper);
                RespEntity res = new RespEntity(new RespEntity.CRespCode(200,"查找成功！"),schedule);
                return res;


            }
            RespEntity res = new RespEntity(new RespEntity.CRespCode(400,"身份验证错误，需要管理员。"));
            return res;

        }
        RespEntity res = new RespEntity(new RespEntity.CRespCode(400,"获取用户信息失败"));
        return res;

    }






}
